package cn.huanba.service.mongo;

import com.mongodb.client.result.UpdateResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * mongo工具类
 */
@Service
public class MongoServiceImpl<T> implements MongoService<T> {

    private Logger log = LoggerFactory.getLogger(MongoServiceImpl.class);

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存数据
     * @param t
     */
    public void save(T t){
        mongoTemplate.save(t);
    }
    /**
     *  删除数据
     * @param clazz
     */
    public void remove(Query query,Class clazz){
        mongoTemplate.remove(query,clazz);
    }
    /**
     * 分页查询数据
     * @param query
     * @param clazz
     * @return
     */
    public List<T> page(int pageNo, int pageSize, Query query, Class clazz){
        // 页码，页长
        int skip = pageSize * (pageNo -1);
        query.skip(skip).limit(pageSize);
        List list = mongoTemplate.find(query, clazz);
        return list;
    }

    public List<T> findList(Query query, Class clazz){
        List list = mongoTemplate.find(query, clazz);
        return list;
    }

    /**
     * 查询总数
     * @param query
     * @param clazz
     * @return
     */
    public long count(Query query, Class clazz){
        long count = mongoTemplate.count(query, clazz);
        return count;
    }


    /**
     * db.books.find({"bookName":"三国演义"})
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T findOne(String key ,Object value, Class clazz){
        Query query = Query.query(Criteria.where(key).is(value));
        T t = (T) mongoTemplate.findOne(query, clazz);
        return t;
    }

    /**
     * db.books.find({"bookName":"三国演义"})
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T findOne(Query query, Class clazz){
        T t = (T) mongoTemplate.findOne(query, clazz);
        return t;
    }

    /**
     *
     * @return
     */
    public long update(Query query, Update update, Class clazz){
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, clazz);
        return updateResult.getModifiedCount();
    }
}
